from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import os
import json
from fastapi import Request  # 添加FastAPI请求类型
import traceback  # 添加堆栈跟踪模块

def setup_logging():
    os.makedirs("logs", exist_ok=True)
    
    # 添加日志器存在性检查
    if not logging.getLogger("api").hasHandlers():
        api_handler = TimedRotatingFileHandler(
            "logs/api.log",
            when="midnight",
            interval=1,
            backupCount=30,
            encoding="utf-8"
        )
        api_handler.setFormatter(logging.Formatter('%(message)s'))
        logging.getLogger("api").addHandler(api_handler)

    if not logging.getLogger("error").hasHandlers():
        error_handler = TimedRotatingFileHandler(
            "logs/error.log",
            when="midnight",
            interval=1,
            backupCount=30,
            encoding="utf-8"
        )
        error_handler.setFormatter(logging.Formatter('%(message)s')) 
        logging.getLogger("error").addHandler(error_handler)
    
    # 设置日志级别
    logging.getLogger("api").setLevel(logging.INFO)
    logging.getLogger("error").setLevel(logging.ERROR)

def log_error(exc: Exception, request: Request):  # 现在Request类型已定义
    error_detail = traceback.format_exception(type(exc), exc, exc.__traceback__)
    logging.getLogger("error").error(json.dumps({
        "timestamp": datetime.now().isoformat(),
        "method": request.method,
        "path": str(request.url),
        "client_ip": request.client.host,
        "status_code": 500,
        "error": str(exc),
        "stack_trace": error_detail
    }, ensure_ascii=False))